package com.faxsun.core.order.service.worklow;

import com.faxsun.core.order.domain.FSOrderItemImpl;
import com.faxsun.core.order.service.FSOrderItemServiceImpl;
import com.faxsun.core.order.service.FSReferralCustomerOrderItemConstants;
import com.faxsun.profile.core.service.FSCustomerService;
import org.apache.commons.lang3.StringUtils;
import org.broadleafcommerce.core.order.domain.OrderItem;
import org.broadleafcommerce.core.order.service.OrderItemService;
import org.broadleafcommerce.core.order.service.call.OrderItemRequestDTO;
import org.broadleafcommerce.core.order.service.workflow.CartOperationRequest;
import org.broadleafcommerce.core.workflow.BaseActivity;
import org.broadleafcommerce.core.workflow.ProcessContext;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.core.service.CustomerService;

import javax.annotation.Resource;

public class FSUpdateReferralCustomerOrderItemActivity extends BaseActivity<ProcessContext<CartOperationRequest>> {

    @Resource(name = "blCustomerService")
    protected CustomerService customerService;

    @Resource(name = "blOrderItemService")
    protected OrderItemService orderItemService;

    @Override
    public ProcessContext<CartOperationRequest> execute(ProcessContext<CartOperationRequest> context) throws Exception {
        CartOperationRequest request = context.getSeedData();
//        OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest();
//        String referralCode = orderItemRequestDTO.getItemAttributes().get(FSReferralCustomerOrderItemConstants.REFERRAL_CODE);
//        Customer referralCustomer = ((FSCustomerService) customerService).readCustomerByReferralCode(referralCode);
        OrderItem orderItem = request.getOrderItem();
        if (orderItem instanceof FSOrderItemImpl) {
            FSOrderItemImpl fsOrderItem = (FSOrderItemImpl) orderItem;
            if (fsOrderItem.getReferralCustomerOrderItemXref() != null) {
                fsOrderItem.getReferralCustomerOrderItemXref().setReferralCredit(
                    ((FSOrderItemServiceImpl) orderItemService).calculateOrderItemReferralCredit(orderItem));
            }
        }

        return context;
    }

//    @Override
//    public boolean shouldExecute(ProcessContext<CartOperationRequest> context) {
//        CartOperationRequest request = context.getSeedData();
//        OrderItemRequestDTO orderItemRequestDTO = request.getItemRequest();
//        if (orderItemRequestDTO.getItemAttributes() == null ||
//            StringUtils.isEmpty(orderItemRequestDTO.getItemAttributes()
//                .get(FSReferralCustomerOrderItemConstants.REFERRAL_CODE))) {
//            return false;
//        } else {
//            return true;
//        }
//    }
}
